package cn.imuduan.wechatrobot;

import cn.zhouyafeng.itchat4j.api.MessageTools;
import cn.zhouyafeng.itchat4j.beans.BaseMsg;
import cn.zhouyafeng.itchat4j.beans.RecommendInfo;
import cn.zhouyafeng.itchat4j.face.IMsgHandlerFace;
import cn.zhouyafeng.itchat4j.utils.MyHttpClinetPlus;
import cn.zhouyafeng.itchat4j.utils.enums.MsgTypeEnum;
import cn.zhouyafeng.itchat4j.utils.tools.DownloadTools;
import com.alibaba.fastjson.JSONObject;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;

/**
 * @author MuDuan
 * @date 2020/1/23 21:13
 */
public class WxRobot implements IMsgHandlerFace {
    Logger logger = Logger.getLogger("WxRobot");
    String url = "https://api.ownthink.com/bot";        // 机器人API接口
    String apiKey = "de890fa6e17a1e7f54c29f6d65491e8c";
    String userId = "BYNXcTfl";

    //收到文本消息
    @Override
    public String textMsgHandle(BaseMsg msg) {
        if (!msg.isGroupMsg()) {
            String result = "";
            String text = msg.getText();
            /*if ("开启大年定时任务".equalsIgnoreCase(text)) {
                new ClassPathXmlApplicationContext("spring-jobs.xml");
                return "开启成功";
            }*/
            Map<String, String> paramMap = new HashMap<String, String>();
            paramMap.put("spoken", text);
            paramMap.put("appid", apiKey);
            paramMap.put("userid", userId);
            try {
                String res = MyHttpClinetPlus.post(url, paramMap, null);
                res = res.substring(res.indexOf("{"));
                JSONObject obj = JSONObject.parseObject(res);//转JSON
                System.out.println(obj.toString());
                if ("success".equalsIgnoreCase(obj.getString("message"))) {
                    //获取json串中指定数据
                    JSONObject data = obj.getJSONObject("data");
                    JSONObject info = data.getJSONObject("info");
                    String json_text = info.getString("text");
                    result = json_text;
                } else {
                    result = "处理有误";
                }
            } catch (Exception e) {
                logger.info(e.getMessage());
            }
            return result;
        }
        return null;
    }

    //收到图片消息
    @Override
    public String picMsgHandle(BaseMsg msg) {
        if (!msg.isGroupMsg()) {
            String fileName = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date());// 这里使用收到图片的时间作为文件名
            String picPath = "D://itchat4j/pic" + File.separator + fileName + ".jpg"; // 调用此方法来保存图片
            DownloadTools.getDownloadFn(msg, MsgTypeEnum.PIC.getType(), picPath); // 保存图片的路径
            return "图片保存成功";
        }
        return null;
    }

    //收到语音消息
    @Override
    public String voiceMsgHandle(BaseMsg msg) {
        if (!msg.isGroupMsg()) {
            String fileName = String.valueOf(new Date().getTime());
            String voicePath = "D://itchat4j/voice" + File.separator + fileName + ".mp3";
            DownloadTools.getDownloadFn(msg, MsgTypeEnum.VOICE.getType(), voicePath);
            return "语音保存成功";
        }
        return null;
    }

    //收到视频消息
    @Override
    public String viedoMsgHandle(BaseMsg msg) {
        if (!msg.isGroupMsg()) {
            String fileName = String.valueOf(new Date().getTime());
            String viedoPath = "D://itchat4j/video" + File.separator + fileName + ".mp4";
            DownloadTools.getDownloadFn(msg, MsgTypeEnum.VIEDO.getType(), viedoPath);
            return "视频保存成功";
        }
        return null;
    }

    //收到名片消息
    @Override
    public String nameCardMsgHandle(BaseMsg msg) {
        return null;
    }

    //收到系统消息
    @Override
    public void sysMsgHandle(BaseMsg msg) {
        String text = msg.getContent();
        logger.info(text);
    }

    //收到好友请求
    @Override
    public String verifyAddFriendMsgHandle(BaseMsg msg) {
        MessageTools.addFriend(msg, true); // 同意好友请求，false为不接受好友请求
        RecommendInfo recommendInfo = msg.getRecommendInfo();
        String nickName = recommendInfo.getNickName();
        String province = recommendInfo.getProvince();
        String city = recommendInfo.getCity();
        String text = "你好，来自" + province + city + "的" + nickName + "， 欢迎添加我为好友！";
        return text;
    }

    //收到文件消息
    @Override
    public String mediaMsgHandle(BaseMsg msg) {
        String fileName = msg.getFileName();
        String filePath = "D://itchat4j/file" + File.separator + fileName; // 这里是需要保存收到的文件路径，文件可以是任何格式如PDF，WORD，EXCEL等。
        DownloadTools.getDownloadFn(msg, MsgTypeEnum.MEDIA.getType(), filePath);
        return "文件" + fileName + "保存成功";
    }

}
